<?php

namespace App\Admin\Controllers;

use App\Models\Shop;
use App\Models\ShopType;
use App\Models\ShopTypeReserve;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\DB;
use App\Admin\Extensions\ExcelExpoter;

class ShopController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Shop::class, function (Grid $grid) {
            $excel = new ExcelExpoter();
            $excel->setAttr(
                ['id' ,'账号','店铺名','余额','销量','评价','外卖模块（0否1是）','预定模块（0否1是）','排队模块（0否1是）','是否推荐（0否1是）'],
                ['id', 'user.mobile','shop_name','user.money','shopinfo.sales','shopinfo.score','is_takeout','is_reserve','is_list','recommend'],'店铺资料'
            );
            $grid->exporter($excel);
            $grid->disableCreateButton();
            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->like('user.mobile', '用户名');
                $filter->like('shop_name', '商家名');
                $filter->equal('is_takeout','外卖模块')->radio([
                    0    => '关',
                    1    => '开',
                ]);
                $filter->equal('is_reserve','预定模块')->radio([
                    0    => '关',
                    1    => '开',
                ]);
                $filter->equal('is_list','排队模块')->radio([
                    0    => '关',
                    1    => '开',
                ]);
            });
            $grid->id('ID')->sortable();
            $grid->model()->where('is_check',1);
            $grid->column('user.mobile', '用户名');
            $grid->column('shop_name', '商家名');
            $grid->column('user.money', '余额')->display(function ($money){
                return "<span class='badge bg-aqua'>$money</span>";
            });
            $grid->column('shopinfo.sales', '销量')->sortable();
            $grid->column('shopinfo.score', '评价')->sortable();
            $grid->is_takeout('外卖模块')->display(function ($is_takeout){
                if($is_takeout==1) {
                    return "<i class='fa fa-check' style='color:#3b9af1'></i>";
                }else{
                    //return "<span class='badge bg-yellow-gradient'>NO</span>";
                    return "<i class='fa fa-close' style='color:#f3c17a'></i>";
                }
            })->sortable();
            $grid->is_reserve('预定模块')->display(function ($is_reserve){
                if($is_reserve==1) {
                    return "<i class='fa fa-check' style='color:#3b9af1'></i>";
                }else{
                    return "<i class='fa fa-close' style='color:#f3c17a'></i>";
                }
            })->sortable();
            $grid->is_list('排队模块')->display(function ($is_list){
                if($is_list==1) {
                    return "<i class='fa fa-check' style='color:#3b9af1'></i>";
                }else{
                    return "<i class='fa fa-close' style='color:#f3c17a'></i>";
                }

            })->sortable();

            $grid->recommend('是否推荐')->display(function ($recommend){
                if($recommend==1) {
                    return "<i class='fa fa-check' style='color:#3b9af1'></i>";
                }else{
                    return "<i class='fa fa-close' style='color:#f3c17a'></i>";
                }

            })->sortable();

            $grid->actions(function ($actions) {
                //$actions->disableDelete();
                $shop_id = $actions->getKey();
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/shop/oneorder?shop_id='.$shop_id.'"><i class="fa fa-eye">查看订单</i></a>');
                //$actions->prepend('&nbsp;&nbsp;<a href="/mobile/shopAdmin/bobo?id='.$shop_id.'"><i class="fa fa-adn">房桌二维码</i></a>');
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/shop/roomtable/newcreate?shop_id='.$shop_id.'"><i class="fa fa-bold">添加房桌</i></a>');
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/shop/dishes/newcreate?shop_id='.$shop_id.'"><i class="fa fa-apple">添加菜式</i></a>');
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/shop/dishes?shop_id='.$shop_id.'"><i class="fa fa-apple">查看菜式</i></a>');
                $actions->prepend('&nbsp;&nbsp;<a href="/admin/shop/menu/create?shop_id='.$shop_id.'"><i class="fa fa-adn">添加菜式分类</i></a>');
                $actions->prepend('<a href="/admin/shop/menu?shop_id='.$shop_id.'"><i class="fa fa-adn">查看菜式分类</i></a>');
            });
            /*$grid->created_at();
            $grid->updated_at();*/
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Shop::class, function (Form $form) {
            $form->saving(function (Form $form) {
                $user = User::find($form->user_id)->first();
                if (!$user) {
                    echo "<script> alert('用户不存在！');history.back(); </script>";
                    die;
                }
                /*//外卖
                if($form->is_takeout == 'on'){
                    $form->is_takeout = 1;
                }else{
                    $form->is_takeout = 0;
                }
                //预定
                if($form->is_reserve == 'on'){
                    $form->is_reserve = 1;
                }else{
                    $form->is_reserve = 0;
                }
                //排队
                if($form->is_list == 'on'){
                    $form->is_list = 1;
                }else{
                    $form->is_list = 0;
                }
                //推荐
                if($form->recommend == 'on'){
                    $form->recommend = 1;
                }else{
                    $form->recommend = 0;
                }

                DB::beginTransaction();
                try {
                    $res = DB::table('shops')->insertGetId([
                        'shop_name' => $form->shop_name,
                        'user_id' => $mobile->id,
                        'shop_phone' => $form->shop_phone,
                        'shop_address' => $form->shop_address,
                        'is_check' => $form->is_check,
                        'is_takeout' => $form->is_takeout,
                        'is_reserve' => $form->is_reserve,
                        'is_list' => $form->is_list,
                        'recommend' => $form->recommend,
                        'note' => $form->note,
                        'latitude' => $form->latitude,
                        'longitude' => $form->longitude,
                        'shop_avatar' => $form->shop_avatar,
                        'shop_pic' => $form->shop_pic,
                        'lience_pic' => $form->lience_pic,
                        'ad_pic' => $form->ad_pic,
                        'id_pic' => $form->id_pic,
                        'id_pic_back' => $form->id_pic_back,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                        DB::table('shop_info')->insert([
                            'shop_id' => $res,
                            'opentime' => $form->shopinfo['opentime'],
                            'minimum' => $form->shopinfo['minimum'],
                            'min_spend' => $form->shopinfo['min_spend'],
                            'spend' => $form->shopinfo['spend'],
                            'spendtime' => $form->shopinfo['spendtime'],
                            'spend_distance' => $form->shopinfo['spend_distance'],
                            'is_wifi' => $form->shopinfo['is_wifi'],
                            'is_room' => $form->shopinfo['is_room'],
                            'is_open' => $form->shopinfo['is_open'],
                            'is_pickup' => $form->shopinfo['is_pickup'],
                            'eating_time' => $form->shopinfo['eating_time'],
                            'gather_discount' => $form->shopinfo['gather_discount'],
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                            ]);
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    echo "<script> alert('创建店铺失败！');history.back(); </script>";die;
                }
                echo "<script> alert('创建店铺成功！');history.back(); </script>";die;*/
            });
            $form->saved(function (Form $form) {
                $shop = Shop::find($form->model()->id);
                if($shop->ad_pic && $form->ad_pic){
                    Shop::where('id',$form->model()->id)->update(['ad_pic'=>'/storage/'.$shop->ad_pic]);
                }
                if($shop->id_pic && $form->id_pic){
                    Shop::where('id',$form->model()->id)->update(['id_pic'=>'/storage/'.$shop->id_pic]);
                }
                if($shop->id_pic_back && $form->id_pic_back){
                    Shop::where('id',$form->model()->id)->update(['id_pic_back'=>'/storage/'.$shop->id_pic_back]);
                }
                if($shop->shop_avatar && $form->shop_avatar){
                    Shop::where('id',$form->model()->id)->update(['shop_avatar'=>'/storage/'.$shop->shop_avatar]);
                }
                if($shop->shop_pic && $form->shop_pic){
                    Shop::where('id',$form->model()->id)->update(['shop_pic'=>'/storage/'.$shop->shop_pic]);
                }
                if($shop->lience_pic && $form->lience_pic){
                    Shop::where('id',$form->model()->id)->update(['lience_pic'=>'/storage/'.$shop->lience_pic]);
                }
            });

            if(request('user_id')) {
                $user_id = request('user_id');
            }else{
                $user_id = Shop::where('id',request()->route()->parameters())->first()->user_id;
            }
            $mobile = User::where('id',$user_id)->first()->mobile;
            $form->display('id', 'ID');
            $form->text('user_id', '用户id')->value($user_id)->rules('required');
            $form->display('user.mobile', '用户名')->value($mobile);
            $form->text('shop_name', '商家名')->rules('required');
            $form->text('shop_phone', '商家电话')->rules('required');
            $form->text('shop_address', '地址')->rules('required');
            $form->text('shopinfo.opentime', '营业时间')->placeholder('如：9:00--14:00,17:00--23:00')->rules('required');
            $form->select('is_check', '审核状态')->options([0 => '未审核', 1 => '已审核']);
            //商家分类
            $ShopType = ShopType::all();
            $res = array();
            foreach ($ShopType as $key => $value) {
                $res[$value['id']] = $value['catname'];
            }
            $form->select('shopinfo.type_id', '商家分类')->options($res);

            //商家菜系分类
            $ShopTypeReserve = ShopTypeReserve::all();
            $r = array();
            foreach ($ShopTypeReserve as $k => $v) {
                $r[$v['id']] = $v['catname'];
            }
            $form->select('shopinfo.type_id', '商家菜系分类')->options($r);

            $is_takeout = [
                'on'  => ['value' => 1, 'text' => '开', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '关', 'color' => 'default'],
            ];
            $form->switch('is_takeout', '外卖模块')->states($is_takeout);
            $is_reserve = [
                'on'  => ['value' => 1, 'text' => '开', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '关', 'color' => 'default'],
            ];
            $form->switch('is_reserve', '预定模块')->states($is_reserve);

            $is_list = [
                'on'  => ['value' => 1, 'text' => '开', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '关', 'color' => 'default'],
            ];
            $form->switch('is_list', '排队模块')->states($is_list);

            $recommend = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];
            $form->switch('recommend', '是否推荐')->states($recommend);

            $form->text('shopinfo.minimum', '最低消费')->default(0);
            $form->text('shopinfo.min_spend', '起送价')->default(0);
            $form->text('shopinfo.spend', '配送费')->default(0);
            $form->text('shopinfo.spendtime', '配送时间(分钟)')->default(0);
            $form->text('shopinfo.spend_distance', '配送半径(单位千米)')->default(0);
            $form->select('shopinfo.is_wifi', '是否wifi')->options([0 => '否', 1 => '是']);
            $form->select('shopinfo.is_room', '是否房间')->options([0 => '否', 1 => '是']);
            $form->select('shopinfo.is_open', '是否营业')->options([0 => '否', 1 => '是']);
            $form->select('shopinfo.is_pickup', '是否自取')->options([0 => '否', 1 => '是']);
            /*$is_wifi = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];
            $form->switch('shopinfo.is_wifi', '是否wifi')->states($is_wifi);

            $is_room = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];
            $form->switch('shopinfo.is_room', '是否房间')->states($is_room);

            $is_open = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];
            $form->switch('shopinfo.is_open', '是否营业')->states($is_open);

            $is_pickup = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'primary'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'default'],
            ];
            $form->switch('shopinfo.is_pickup', '是否自取')->states($is_pickup);*/

            $form->text('shopinfo.eating_time', '用餐时间(预定,小时)')->default(0);
            $form->text('shopinfo.gather_discount', '用餐价格百分比')->default(0);
            //$form->multipleSelect('', '商铺分类')->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);
            $form->textarea('note', '商铺介绍')->rows(3)->rules('max:70');
            $form->text('longitude', '经度')->rules('required');
            $form->text('latitude', '纬度')->rules('required');
            /*if(request()->route()->parameters()) {
                $form->map('latitude', 'longitude', '地图');
            }*/
            $form->image('shop_avatar', '商家头像')->move("user_$user_id/info")->uniqueName()->rules('required');
            $form->image('shop_pic', '门面照')->move("user_$user_id/info")->uniqueName()->rules('required');
            $form->image('ad_pic', '菜单广告图')->move("user_$user_id/info")->uniqueName();
            $form->image('lience_pic', '营业执照')->move("user_$user_id/info")->uniqueName()->rules('required');
            $form->image('id_pic', '证件照')->move("user_$user_id/info")->uniqueName();
            $form->image('id_pic_back', '证件照(反面)')->move("user_$user_id/info")->uniqueName();
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }
}
